-- UIShipMain
-- Created by chengb Jun/4/2015
-- 幽灵船主界面

require "game/ui/form/ghost_ship/UIShipSkillLearn"
require "game/ui/form/ghost_ship/UIShipSkillUpgrade"
require "game/ui/form/common/UIImproveNotify"

UIShipMain = class("UIShipMain", function()
    return cc.Layer:create();
end);

function UIShipMain.create(ship)
    return UIShipMain.new(ship);
end

-- 光效缩放比例
local EFFECT_SCALE = 1.5;

-- 构造函数
function UIShipMain:ctor(ship)
    self:setName("UIShipMain");
    local node = cc.CSLoader:createNode("layout/ghost_ship/ShipMain.csb");
    self:addChild(node);
    self.node = node;

    self:setLocalZOrder(UIMgr.TOP_MENU_ZORDER + 1);

    -- 记录幽灵船对象
    self.ship = ship;

    -- 注册事件处理回调函数
    self:registerEventCallback()

    -- 注册点击事件
    self:registerTouchEvent();

    -- 初始化窗口
    self:initForm();

    -- 重绘
    self:redraw();

    -- 适配
    self:resize();
end

-- 适配
function UIShipMain:resize()
    local node = self.node;

    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end

-- 注册事件处理回调函数
function UIShipMain:registerEventCallback()
    -- 关注幽灵船学习技能事件
    EventMgr.register("UIShipMain", event.LEARN_SHIP_SKILL, function(args)
        -- 提示
        local skillId = args.skillId;
        local skillName = SkillM.query(skillId, "name");
        local content = string.format(getLocStr("ship_learn_skill_succ"), skillName);
        self:showImproveNotify(getLocStr("gain_skill_title"), content);
    end);

    -- 关注幽灵船技能升级技能事件
    EventMgr.register("UIShipMain", event.UPGRADE_SHIP_SKILL, function(args)
        -- 显示升级特效界面
        local skillId = args.skillId;
        local skillName = SkillM.query(skillId, "name");
        local level = SkillM.query(skillId, "level") + 1;
        local content = string.format(getLocStr("ship_upgrade_skill_succ"), skillName, level);
        self:showImproveNotify(getLocStr("level_up_title"), content);
    end);

    self:registerScriptHandler(function(eventType)
        if eventType == "exit" then
            cclog("UIShipMain 界面析构清理");

            -- 移除所有事件关注
            EventMgr.removeAll("UIShipMain");

            if UIDungeonMgr:getCurLevel() then
                UIDungeonMgr:getCurLevel():showMenu();
            end

        elseif eventType == "enter" then
            if UIDungeonMgr:getCurLevel() then
                UIDungeonMgr:getCurLevel():hideMenu();
            end
        end
    end);
end

-- 显示能力提升特效界面
function UIShipMain:showImproveNotify(title, content)
    UIMgr.getCurrentScene():removeFormByName("UIImproveNotify");
    local uiNotify = UIImproveNotify.create(title, content);
    UIMgr.getCurrentScene():addForm(uiNotify);
end

-- 注册点击事件
function UIShipMain:registerTouchEvent()
    -- 注册返回按钮点击事件
    local btnBack = findChildByName(self.node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_return");
            -- 关闭当前界面
            UIMgr.getCurrentScene():removeFormByName("UIShipMain");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));
end

-- 初始化窗口
function UIShipMain:initForm()
    local skillPanel = findChildByName(self.node, "CT/skill_panel");
    self.skillPanel = skillPanel;

    local panelWidth  = skillPanel:getContentSize().width;
    local panelHeight = skillPanel:getContentSize().height;

    local posY = panelHeight/2;

    local iconWidth  = 94;
    local iconHeight = 94;

    -- 获取所有技能
    local skills = GhostShipM.query(self.ship.classId, "skills");
    local skillNum = #skills;
    if skillNum == 0 then
        return;
    end

    -- 图标与图标直接的间距
    local gap = 25;
    local leftWGap = 20;

    for i = 1, skillNum do
        -- 暂时复用魔藤的技能图标
        local child = cc.CSLoader:createNode("layout/bine/SkillIcon.csb");
        child:setName("skill" .. i);
        local posX = iconWidth / 2 + (i - 1)*(iconWidth + gap) + leftWGap;
        child:setPosition(posX, posY);
        skillPanel:addChild(child);

        -- 注册技能框点击事件
        local skillFrame = findChildByName(child, "frame");
        skillFrame:setTouchEnabled(true);
        local function onFrameClick(sender, eventType)
            if eventType == ccui.TouchEventType.ended then
                AudioM.playFx("button_click");
                local skillId = child.skillId;
                if self.ship:ownSkill(skillId) then
                    -- 已学会的技能
                    -- 打开升级界面
                    UIMgr.getCurrentScene():removeFormByName("UIShipSkillUpgrade");
                    local uiForm = UIShipSkillUpgrade.create(skillId);
                    UIMgr.getCurrentScene():addForm(uiForm);
                else
                    -- 打开学习界面
                    UIMgr.getCurrentScene():removeFormByName("UIShipSkillLearn");
                    local uiForm = UIShipSkillLearn.create(skillId);
                    UIMgr.getCurrentScene():addForm(uiForm);
                end
            end
        end
        skillFrame:addTouchEventListener(onFrameClick);
    end

    -- 旋转光圈
    local actionBy = cc.RotateBy:create(30, 360);
    local light = findChildByName(self.node, "CT/left_part/light");
    local sequenceAction = cc.Sequence:create(actionBy);
    light:runAction(cc.RepeatForever:create(sequenceAction));

    -- 初始化光效节点
    local effectNode  = findChildByName(self.node, "CT/left_part/effect_node");
    local effectNode2 = findChildByName(self.node, "CT/left_part/effect_node2");
    effectNode:setScale(EFFECT_SCALE);
    effectNode2:setScale(EFFECT_SCALE);
end

-- 重绘
function UIShipMain:redraw()
    -- 显示幽灵船名称
    local classId = self.ship.classId;
    local name = GhostShipM.query(classId, "name");
    local titleLabel = findChildByName(self.node, "CT/common_bg/bg/title_label");
    titleLabel:setString(name);
    TextStyleM.setArtWordTitleStyle(titleLabel);

    -- 显示幽灵船描述
    local descTitleLabel = findChildByName(self.node, "CT/desc_title");
    local descLabel = findChildByName(self.node, "CT/desc");
    local desc2Label = findChildByName(self.node, "CT/desc2");
    local descTitle = getLocStr("ghost_ship_desc_title");
    TextStyleM.setTextStyle(descTitleLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_BEIGE, false, -1);
    TextStyleM.setTextStyle(descLabel, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_BEIGE);
    TextStyleM.setTextStyle(desc2Label, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_DARK_BROWN);
    local desc = GhostShipM.query(classId, "desc");
    descTitleLabel:setString(descTitle);
    descLabel:setString(desc);
    local cycle = GhostShipM.autoAttackRound(self.ship);
    local attackDesc = string.format(getLocStr("ship_attack_tip"), cycle);
    desc2Label:setString(attackDesc);

    -- 显示等级
    local level = self.ship:getLevel();
    local levelLabel = findChildByName(self.node, "CT/level_node/level");
    TextStyleM.setTextStyle(levelLabel, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_BEIGE, false, -1);
    levelLabel:setString(string.format(getLocStr("ship_level_format"), level));

    local icon = findChildByName(self.node, "CT/level_node/icon");
    icon:loadTexture("images/ui/level/sailor.png");

    -- 适配描述的位置
    self:alignDescLabel(descLabel, desc2Label);

    -- 显示幽灵船模型
    self:redrawModel();

    -- 显示幽灵船属性
    self:redrawAttrib();

    -- 显示幽灵船技能
    self:redrawSkill();
end

-- 适配描述的位置
function UIShipMain:alignDescLabel(desc1, desc2)
    -- desc1的Y轴位置
    local positionY = desc1:getPositionY();

    -- desc1文本控件的高度
    local labelHeight = getRealContentSize(desc1).height;

    -- 设置desc2的位置
    desc2:setPositionY(positionY - labelHeight - 6);
end

-- 显示幽灵船模型
function UIShipMain:redrawModel()
    local leftPart = findChildByName(self.node, "CT/left_part");

    local modelNode = findChildByName(leftPart, "model_node");
    modelNode:removeAllChildren();

    -- 创建幽灵船模型
    createShipModel(modelNode, self.ship.classId)
 end

-- 显示幽灵船属性
function UIShipMain:redrawAttrib()
    local valueLabel, nameLabel;
    local rightPart = findChildByName(self.node, "CT/common_bg/right_part");

    -- 幽灵船只有攻击和魔力，没有生命和魔法
    local attack = self.ship:getAttack();
    local magic  = self.ship:getMagic();

    -- 攻击
    nameLabel = findChildByName(rightPart, "attack_node/name");
    valueLabel= findChildByName(rightPart, "attack_node/value");
    TextStyleM.setTextStyle(nameLabel, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_BEIGE, false, -1);
    TextStyleM.setTextStyle(valueLabel, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_BEIGE, false, -1);
    nameLabel:setString(getLocStr("attack"));
    valueLabel:setString(tostring(attack));

    -- 生命
    local nameLabel= findChildByName(rightPart, "hp_node/name");
    local valueLabel= findChildByName(rightPart, "hp_node/value");
    TextStyleM.setTextStyle(nameLabel, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_BEIGE, false, -1);
    TextStyleM.setTextStyle(valueLabel, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_BEIGE, false, -1);
    nameLabel:setString(getLocStr("hp"));
    valueLabel:setString("--");

    -- 魔力
    local nameLabel= findChildByName(rightPart, "dodge_node/name");
    local valueLabel= findChildByName(rightPart, "dodge_node/value");
    local iconImg = findChildByName(rightPart, "dodge_node/icon");
    iconImg:loadTexture(getSmallAttribIconPath("magic"));
    TextStyleM.setTextStyle(nameLabel, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_BEIGE, false, -1);
    TextStyleM.setTextStyle(valueLabel, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_BEIGE, false, -1);
    nameLabel:setString(getLocStr("magic"));
    valueLabel:setString(tostring(magic));

    -- 魔法
    local nameLabel= findChildByName(rightPart, "accuracy_node/name");
    local valueLabel= findChildByName(rightPart, "accuracy_node/value");
    local iconImg = findChildByName(rightPart, "accuracy_node/icon");
    iconImg:loadTexture(getSmallAttribIconPath("mp"));
    TextStyleM.setTextStyle(nameLabel, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_BEIGE, false, -1);
    TextStyleM.setTextStyle(valueLabel, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_BEIGE, false, -1);
    nameLabel:setString(getLocStr("mp"));
    valueLabel:setString("--");

    local addList = {};

    -- 攻击+N效果
    local modelNode = findChildByName(self.node, "CT/left_part/model_node");
    if self.lastAttack ~= nil then
        local addValue =  attack - self.lastAttack;
        table.insert(addList, { "attack", addValue });
    end
    self.lastAttack = attack;

    -- 魔力+N效果
    if self.lastMagic ~= nil then
        local addValue = magic - self.lastMagic;
        table.insert(addList, { "magic", addValue });
    end
    self.lastMagic = magic;

    -- 播放特效
    for i, arr in pairs(addList) do
        local attrib = arr[1];
        local value  = arr[2];
        if value > 0 then
            local function callFunc()
                playAttribUpEffect(modelNode, value, cc.p(0, 50), attrib);
            end
            performWithDelay(self, callFunc, 2 + 0.5*i);
            i = i + 1;
        end
    end
end

-- 获取技能框控件
function UIShipMain:getSkillChild(skillId)
    -- 获取所有技能
    local skills = GhostShipM.query(self.ship.classId, "skills");
    local skillNum = #skills;
    for i = 1, #skills do
        local child = findChildByName(self.skillPanel, "skill" .. i);
        if SkillM.findBaseSkill(child.skillId) == SkillM.findBaseSkill(skillId) then
            return child;
        end
    end

    return nil;
end

-- 显示幽灵船技能
function UIShipMain:redrawSkill()
    -- 获取所有技能
    local skills = GhostShipM.query(self.ship.classId, "skills");

    local skillNum = #skills;
    if skillNum == 0 then
        return;
    end

    local learnedSkills = self.ship:getAllSkills();

    for i, skillId in pairs(skills) do
        local child    = findChildByName(self.skillPanel, "skill" .. i);
        local iconImg  = findChildByName(child, "icon");
        local starNode = findChildByName(child, "star_node");
        local frame    = findChildByName(child, "frame");

        local skillInfo = SkillM.query(skillId);

        if not skillInfo then
            error(string.format("获取不到技能(%d)配置", skillId));
        end

        -- 绘制技能图标
        iconImg:loadTexture(getSkillIconPath(skillInfo["icon"]));

        setGrayMode(iconImg, false);

        -- 如果该技能已学习
        if self.ship:ownSkill(skillId) then
            -- 获取技能等级，并根据等级获取对应的技能编号
            local level = self.ship:getSkillLevel(skillId);
            child.skillId = SkillM.findSkill(skillId, level);

            -- 绘制技能星级
            local lightStarPath = "images/ui/symbol/career_star_01.png";
            local layer = createStarLayer(level, lightStarPath, "center", -0.5, 0.825);

            if layer then
                starNode:removeAllChildren();
                starNode:addChild(layer);
            end


            setGrayMode(iconImg, false);

            frame:setOpacity(255);
        else
            child.skillId = skillId;

            -- 未学习的技能图标需要灰化处理
            setGrayMode(iconImg, true);

            -- 框需要半透明
            frame:setOpacity(100);
        end

        -- 如果满足学习或升级的条件，则显示加号蒙版
        if true == GhostShipM.canLearnSkill(child.skillId) then
            -- 可学习
            -- 播放气泡动画
            playBubbleAnima(iconImg, false);
        elseif true == GhostShipM.canUpgradeSkill(child.skillId) then
            -- 可升级
            -- 播放气泡动画
            playBubbleAnima(iconImg, false);
        else
            iconImg:stopAllActions();
        end
    end
end






